package com.nku.mason.lucene.fy;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nku.mason.lucene.fy.service.ArticleService;
import com.nku.mason.lucene.fy.vo.Article;
import com.nku.mason.lucene.fy.vo.PageBean;

public class PageController extends HttpServlet {

	private static final long serialVersionUID = -1185603718827087328L;
	private ArticleService articleService = new ArticleService();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req,resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//因为没有设置编码的filter，所以这里进行编码设置
		req.setCharacterEncoding("UTF-8");
		//读取请求参数(页数，分页大小，查询关键字/lucene必须有关键字！)
		String currPageNum = req.getParameter("currPageNum");
		String pageSize = req.getParameter("pageSize");
		String keyword = req.getParameter("keyword");
		//处理参数,赋默认值
		if (keyword == null || keyword.trim().length() == 0) {
			keyword = "";
		}
		if (currPageNum == null || currPageNum.trim().length() == 0) {
			currPageNum = "1";
		}
		if (pageSize == null || pageSize.trim().length() ==0) {
			pageSize = "1";
		}
		//调用Service层，获取分页对象PageBean，存入req域
		//将查询关键字也存在req域，用于回显
		try {
			PageBean<Article> page = articleService.getPage(keyword, Integer.parseInt(currPageNum), Integer.parseInt(pageSize));
			req.setAttribute("PAGE", page);
			req.setAttribute("KEYWORD", keyword);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//将请求转发至list.jsp,在list.jsp中输出查询结果
		req.getRequestDispatcher("/list.jsp").forward(req, resp);
	}
}
